Learn Perl in 10 minutes
Perl is a powerful, high-level programming language known for its text processing capabilities and flexibility. Originally developed for system administration tasks, Perl has evolved into a versatile language used for web development, network programming, and more. This tutorial covers Perl’s core concepts to help you quickly learn the language.
1. Writing Your First Perl Program
Let’s start with a simple program. Create a file named hello.pl and enter the following code:
#!/usr/bin/perl
print "Hello, World!\n";
Save the file and run the following command in the terminal:
perl hello.pl
The output will be:
Hello, World!
This simple program demonstrates Perl’s basic output functionality. The print function is used to display text information in the console.
2. Basic Syntax
Perl’s syntax is flexible and expressive, with several distinctive features.
# This is a comment
print "Hello, World!\n";
Basic syntax rules in Perl:
- Comments: Single-line comments start with
# - Statements: End with semicolon
; - Shebang Line:
#!/usr/bin/perlat the top of script files - Variables: Use special characters to denote variable types (
$,@,%) - String Quotes: Can use single quotes
'or double quotes"
3. Variables and Data Types
In Perl, variables are dynamically typed and use special characters to denote their type.
Scalar variables (single values):
$name = "Alice";
$age = 25;
$temperature = 36.5;
$is_active = 1; # 1 for true, empty string for false
Array variables (ordered lists):
@fruits = ("apple", "banana", "cherry");
@numbers = (1, 2, 3, 4, 5);
Hash variables (key-value pairs):
%person = (
"name" => "John",
"age" => 30,
"city" => "New York"
);
3.1 Scalar Variables
Scalars hold single values like strings, numbers, or references.
# String operations
$text = "Perl Programming";
print length($text); # String length
print uc($text); # Convert to uppercase
print lc($text); # Convert to lowercase
print substr($text, 0, 4); # Extract substring
# Numeric operations
$x = 10;
$y = 3;
print $x + $y; # 13
print $x - $y; # 7
print $x * $y; # 30
print $x / $y; # 3.333...
print $x % $y; # 1 (modulo)
3.2 Array Variables
Arrays are ordered collections that can hold multiple values.
@colors = ("red", "green", "blue");
# Accessing array elements
print $colors[0]; # "red" (use $ for single element)
print $colors[1]; # "green"
print $colors[-1]; # "blue" (last element)
# Array operations
push(@colors, "yellow"); # Add to end
pop(@colors); # Remove from end
shift(@colors); # Remove from beginning
unshift(@colors, "purple"); # Add to beginning
# Array functions
print scalar(@colors); # Number of elements
print $#colors; # Last index
3.3 Hash Variables
Hashes are collections of key-value pairs.
%student = (
name => "Alice",
age => 20,
major => "Computer Science"
);
# Accessing hash elements
print $student{"name"}; # "Alice"
print $student{age}; # 20
# Hash operations
$student{"gpa"} = 3.8; # Add new key-value pair
delete $student{"age"}; # Remove key-value pair
# Hash functions
@keys = keys %student; # Get all keys
@values = values %student; # Get all values
4. Control Flow
Perl provides several control flow statements to manage program execution.
4.1 if Statements
The if statement evaluates a condition and executes its block if the condition is true.
$age = 20;
if ($age >= 18) {
print "Adult\n";
} elsif ($age >= 13) {
print "Teen\n";
} else {
print "Child\n";
}
# One-line if
print "Adult\n" if $age >= 18;
4.2 unless Statements
unless is the opposite of if - executes when the condition is false.
$age = 15;
unless ($age >= 18) {
print "Not an adult\n";
}
# One-line unless
print "Not an adult\n" unless $age >= 18;
4.3 Loops
Perl supports various loop constructs.
while loop:
$count = 0;
while ($count < 5) {
print "Count: $count\n";
$count++;
}
for loop:
for ($i = 0; $i < 5; $i++) {
print "i = $i\n";
}
foreach loop:
@fruits = ("apple", "banana", "cherry");
foreach $fruit (@fruits) {
print "Fruit: $fruit\n";
}
# Using default variable $_
foreach (@fruits) {
print "Fruit: $_\n";
}
last and next:
foreach (1..10) {
last if $_ == 5; # Exit loop
next if $_ % 2 == 0; # Skip even numbers
print "$_\n"; # Output: 1, 3
}
5. Subroutines
Subroutines in Perl are defined using the sub keyword.
Basic Subroutine Definition:
sub greet {
my $name = shift;
return "Hello, $name!";
}
# Calling the subroutine
$message = greet("John");
print $message;
Using Parameters:
sub add_numbers {
my ($a, $b) = @_;
return $a + $b;
}
$result = add_numbers(5, 3);
print "Sum: $result\n";
Default Parameters:
sub greet {
my ($name, $greeting) = @_;
$greeting = "Hello" unless defined $greeting;
return "$greeting, $name!";
}
print greet("Alice"); # "Hello, Alice!"
print greet("Bob", "Hi"); # "Hi, Bob!"
6. Regular Expressions
Perl is famous for its powerful regular expression capabilities.
Basic Pattern Matching:
$text = "Hello, World!";
if ($text =~ /Hello/) {
print "Found 'Hello'\n";
}
# Case-insensitive matching
if ($text =~ /world/i) {
print "Found 'world' (case-insensitive)\n";
}
Substitution:
$text = "I like cats and cats are cute";
$text =~ s/cats/dogs/g; # Replace all occurrences
print "$text\n"; # "I like dogs and dogs are cute"
Extracting Matches:
$email = "[email protected]";
if ($email =~ /(\w+)@(\w+\.\w+)/) {
print "Username: $1\n"; # "user"
print "Domain: $2\n"; # "example.com"
}
7. File Operations
Perl provides simple methods for reading and writing files.
Reading Files:
# Read entire file
open(my $fh, '<', 'example.txt') or die "Cannot open file: $!";
my $content = do { local $/; <$fh> };
close($fh);
print $content;
# Read line by line
open(my $fh, '<', 'example.txt') or die "Cannot open file: $!";
while (my $line = <$fh>) {
print $line;
}
close($fh);
Writing Files:
# Write to file
open(my $fh, '>', 'output.txt') or die "Cannot open file: $!";
print $fh "Hello, Perl!\n";
close($fh);
# Append to file
open(my $fh, '>>', 'output.txt') or die "Cannot open file: $!";
print $fh "Appending new content.\n";
close($fh);
8. Built-in Functions
Perl comes with many useful built-in functions.
String Functions:
$text = " Perl Programming ";
print length($text); # String length
print uc($text); # Convert to uppercase
print lc($text); # Convert to lowercase
print substr($text, 0, 4); # Extract substring
print index($text, "Prog"); # Find substring position
Array Functions:
@numbers = (3, 1, 4, 1, 5, 9, 2);
print join(", ", sort @numbers); # "1, 1, 2, 3, 4, 5, 9"
print join(", ", reverse @numbers); # "2, 9, 5, 1, 4, 1, 3"
# Filter array
@filtered = grep { $_ > 3 } @numbers;
print join(", ", @filtered); # "4, 5, 9"
# Transform array
@doubled = map { $_ * 2 } @numbers;
print join(", ", @doubled); # "6, 2, 8, 2, 10, 18, 4"
Hash Functions:
%person = (name => "Alice", age => 25, city => "New York");
@keys = keys %person; # Get all keys
@values = values %person; # Get all values
# Check if key exists
if (exists $person{age}) {
print "Age exists\n";
}
9. Perl Modules
Perl has a rich ecosystem of modules available through CPAN.
Using Core Modules:
use strict;
use warnings;
use Data::Dumper;
%data = (name => "Bob", age => 30);
print Dumper(\%data); # Pretty print data structure
Installing and Using CPAN Modules:
# Install module from CPAN
cpan install JSON
use JSON;
# Parse JSON
$json_string = '{"name": "Alice", "age": 25}';
$person = decode_json($json_string);
print $person->{name}; # "Alice"
# Generate JSON
$person_hash = { name => "Bob", age => 30 };
$json_output = encode_json($person_hash);
print $json_output; # {"name":"Bob","age":30}
10. Perl Style Guide
Perl has community conventions that promote clean, readable code.
Indentation: Use 4 spaces for indentation.
Variable Naming:
- Use descriptive names
- Follow snake_case convention
- Use meaningful variable names
Code Organization:
- Use
use strict;anduse warnings;at the top of scripts - Declare variables with
myto limit scope - Use meaningful subroutine names
Documentation:
- Use POD (Plain Old Documentation) for documenting code
- Include comments for complex logic
Perl’s flexibility and powerful text processing capabilities make it an excellent choice for system administration, web development, and data processing tasks. Its rich ecosystem of modules and strong community support continue to make it relevant in modern programming environments.
